# -*- coding: utf-8 -*-
import os
import sys
from Qt import __binding__
from Qt.QtCore import *
from Qt.QtWidgets import *


def engine():
    app = sys.executable
    app_basename = os.path.basename(app)
    app_name = os.path.splitext(app_basename)[0]
    if "Nuke" in app_name:
        app_name = "nuke"
    elif "houdini" in app_name:
        app_name = "houdini"
    elif "maya" in app_name:
        app_name = "maya"
    elif "clarisse" in app_name:
        app_name = "clarisse"
    return app_name


def selectedNodes():
    eng = engine()
    if eng == "maya":
        import maya.cmds as mc
        return mc.ls(sl=1)
    elif eng == "nuke":
        import nuke
        return nuke.selectedNodes()
    elif eng == "houdini":
        import hou
        return hou.selectedNodes()
    elif eng == "clarisse":
        import ix
        return [i.get_full_name() for i in ix.selection]
    else:
        # todo: add other dcc functions
        print "add other dcc functions"
    return False


def selectedNodeNames():
    names = list()
    eng = engine()
    nodes = selectedNodes()
    if not nodes:
        return names
    if eng == "maya":
        return nodes
    elif eng == "nuke":
        names = [node.knob("name").getValue() for node in nodes]
    elif eng == "houdini":
        names = [node.name() for node in nodes]
    elif eng == "clarisse":
        return nodes
    return names


def get_maya_win(module="PySide"):
    """
    get a QMainWindow Object of maya main window
    :param module (optional): string "PySide"(default) or "PyQt4"
    :return main_window: QWidget or QMainWindow object
    """
    import maya.OpenMayaUI as mui
    prt = mui.MQtUtil.mainWindow()
    if module == "PyQt":
        import sip
        main_window = sip.wrapinstance(long(prt), QObject)
    elif module in ["PySide"]:
        if __binding__ in ["PySide"]:
            import shiboken
        elif __binding__ in ["PySide2"]:
            import shiboken2 as shiboken
        main_window = shiboken.wrapInstance(long(prt), QWidget)
    elif module == "mayaUI":
        main_window = "MayaWindow"
    else:
        raise ValueError('param "module" must be "mayaUI" "PyQt4" or "PySide"')
    return main_window


def get_nuke_win():
    main_window = None
    app = QApplication.instance()
    for widgets in app.topLevelWidgets():
        if widgets.metaObject().className() == "Foundry::UI::DockMainWindow":
            main_window = widgets
    return main_window


def get_houdini_win():
    import hou
    return hou.ui.mainQtWindow()


def get_parent_win():
    parent_win = None
    eng = engine()
    if eng == "maya":
        parent_win = get_maya_win("PySide")
    elif eng == "nuke":
        parent_win = get_nuke_win()
    elif eng == "houdini":
        parent_win = get_houdini_win()
    elif eng == "python":
        return
    else:
        # todo
        print "add method to how to get main window."
    return parent_win
